Stop background worker

Jordan Halgunseth 1 Reputation point
2024-05-13T16:09:43.7+00:00

I am using C#.

I have a that has a background worker reading a file.

How do I stop it before it is finished by pressing esc key.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,466 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,399 questions
{count} votes

1 answer

Sort by: Most helpful
  1. KOZ6.0 5,295 Reputation points
    2024-05-13T17:52:08.9233333+00:00

    This is a sample. While looping the DoWork event, check CancellationPending to finish processing.

    using System;
    using System.ComponentModel;
    using System.Threading;
    using System.Windows.Forms;
    
    public partial class Form1 : Form
    {
        public Form1() {
            InitializeComponent();
            AcceptButton = btnOK;
            CancelButton = btnCancel;
            SetupButton(true);
            backgroundWorker1.WorkerSupportsCancellation = true;
        }
    
        private void SetupButton(bool value) {
            btnOK.Enabled = value;
            btnCancel.Enabled = !value;
        }
    
        private void btnOK_Click(object sender, EventArgs e) {
            SetupButton(false);
            backgroundWorker1.RunWorkerAsync();
        }
    
        private void btnCancel_Click(object sender, EventArgs e) {
            backgroundWorker1.CancelAsync();
        }
    
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
            for (int i = 0; i < 1000; i++) {
                if (backgroundWorker1.CancellationPending) {
                    e.Cancel = true;
                    break;
                }
                Thread.Sleep(10);
            }
        }
    
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
            if (e.Cancelled) {
                MessageBox.Show("Cancelled");
            } else {
                MessageBox.Show("Complete");
            }
            SetupButton(true);
        }
    }